import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import Config

db = SQLAlchemy()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    with app.app_context():
        db_dir = os.path.dirname(app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', ''))
        os.makedirs(db_dir, exist_ok=True)  # 关键修复点
        os.chmod(db_dir, 0o755)  # 设置权限（Linux/Mac）
    # 初始化数据库
    db.init_app(app)
    
    # 注册路由
    from .routes import bp as main_bp
    app.register_blueprint(main_bp)

    # 注册 CLI 命令
    from .cli import register_cli
    register_cli(app)

    # 确保数据目录存在
    with app.app_context():
        os.makedirs(os.path.join(app.root_path, 'data'), exist_ok=True)

    return app